// @ts-nocheck
import { useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import echarts from '@/plugins/echarts';

const ChartUnit = (
  {
    width = '100%',
    height = '300px',
    backgroundColor = 'transparent',
    style = {},
    option,
    events = [],
    ...restProps
  } = {},
  ref
) => {
  const chartRef = useRef(null);
  const instanceRef = useRef(null);

  useImperativeHandle(ref, () => instanceRef);

  useEffect(() => {
    instanceRef.current = echarts.init(chartRef.current);
    events.forEach(({ event, handler }) => {
      instanceRef.current.on(event, handler);
    });
    const handleResize = () => {
      instanceRef.current.resize();
    };
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      events.forEach(({ event, handler }) => {
        instanceRef.current.off(event, handler);
      });
      instanceRef.current.dispose();
    };
  }, []);

  useEffect(() => {
    instanceRef.current.setOption(option, true);
    instanceRef.current.resize();
  }, [option]);

  return <div style={{ width, height, backgroundColor, ...style }} ref={chartRef} {...restProps} />;
};

export default forwardRef(ChartUnit);
